var md5 = require('md5.js');
var baseUrl = 'https://www.pingecai.com/';
var safecode = 'MixDJ*&fTA8!fKKsDS#@!$G@#$!#SC!';

/**
 * 接口请求
 * @parma   string   model    接口请求方法
 * @param   string   data     请求参数（json类型）
 * @param   string   method   请求方式（默认GET）
 * @return  function result   返回值
 */
function apiRequest(model, data, result, method = "POST") {
    checkNet();
    if (data == '') {
        data = {};
    }
    data = Object.assign(data,encrypt());
    var url = baseUrl + model;
    var header = { 'content-type': 'application/json' };
    if (method == "POST") {
        header = { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' };
    }
    wx.request({
        url: url,
        data: data,
        method: method,
        header: header,
        complete: function (res) {
            if (res.errMsg.indexOf("request:fail") >= 0) {
                failRequest();
            }
            if (res.statusCode !== 200) {
                failRequest();
            }
            if (typeof result == 'function') {
                result(res.data);
            }
        }
    });
}

/**
 * 下拉刷新(数据重载)
 */
function refresh(obj) {
    wx.showNavigationBarLoading()
    obj.onLoad(obj.options);
    setTimeout(function () {
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh()
    }, 500)

}


/**
 * 加密
 */
function encrypt() {
    var result = {
        timestamps: String(getTimestamps()),
        nonce: randomNonce()
    }
    result.sign = result.timestamps + result.nonce + '|' + safecode;
    result.sign = md5.md5(result.sign);
    result.sign = result.sign.toUpperCase();

    return result;
}

/**
 * 将中文转为16进制的unicode编码格式
 */
function chineseToUnicode(str){
    var result = ''
    for (var i = 0; i < str.length; i++){
　　　　 if (str.charCodeAt(i) > 255) //如果是汉字，则字符串长度加2
            result += "\\u" + str.charCodeAt(i).toString(16);
        else
            result += str.charAt(i);
　　}
    return result;
}
/**
 * 将16进制的unicode编码格式的字符串转为中文
 */
function UnicodeTochinese(str) {
    return unescape(str.replace(/\\u/gi, '%u'));
}

/**
 * 获取时间戳(精确到秒)
 */
function getTimestamps() {
    return Date.parse(new Date()) * 0.001;
    //return new Date().getTime();
}

/**
 * 生成随机字符串
 */
function randomNonce() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 8; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text
}

/**
 * 检测网络
 */
function checkNet() {
    wx.getNetworkType({
        success: function (res) {
        if (res.networkType === 'none') {
            wx.navigateTo({
                url: '../nonet/nonet',
            })
        }
        },
    })
}

/**
 * 网络请求失败
 */
function failRequest() {
    wx.redirectTo({
        url: '../error/error',
    })
}

/**
 * 网络返回非200
 */
function networkAnomaly() {
    wx.redirectTo({
        url: '../error/error',
    })
}

/**
 * 用户登录
 */
function login(){
    return new Promise(function(resolve,reject){
        wx.login({
            success: function (res) {
                //获取登录用户Openid
                apiRequest('api/user/getOpenid', { code: res.code }, function (result) {
                    resolve(result)
                });
            }
        })
    })
}


/**
 * 导航
 * @param  string  longitude
 * @param  string  latitude
 * @param  string  name
 * @pram   string  address
 */
function mapTap(latitude,longitude,name,address) {
    wx.openLocation({
        latitude: parseFloat(latitude),
        longitude: parseFloat(longitude),
        scale: 18,
        name: name,
        address: address
    });
}

/**
 * 获取当前日期
 */
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var year = date.getFullYear();
    var month = parseInt(date.getMonth() + 1);
    var strDate = parseInt(date.getDate());
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}

/**
 * 获取当前时间
 */
function getNowFormattime() {
    var date = new Date();
    var seperator1 = ":";
    var hour = parseInt(date.getHours());
    var minutes = parseInt(date.getMinutes());
    if (hour >= 1 && hour <= 9) {
        hour = "0" + hour;
    }
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
    }
    var currenttime = hour + seperator1 + minutes;
    return currenttime;
}

/**
 * 获取当前时间前后指定的某一天
 */
function getAppointDate(aa) {
    var date1 = new Date(),
        time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate();//time1表示当前时间
    var date2 = new Date(date1);
    var year = date2.getFullYear();
    date2.setDate(date1.getDate() + aa);
    var month = parseInt(date2.getMonth() + 1);
    var strDate = parseInt(date2.getDate());
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var time = year + "-" + month + "-" + strDate;
    return time;
}

/**
 * 获取指定时间前后指定的某一天
 */
function getAppoint(appointDate,num) {
    try{
        var date = new Date(Number(new Date(appointDate)) + 1000*60*60*24*num);
    }catch(e){
        return false;
    }
    var year = date.getFullYear();
    var month = parseInt(date.getMonth() + 1);
    var strDate = parseInt(date.getDate());
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var time = year + "-" + month + "-" + strDate;
    return time;
}

/**
 * 获取某个时间的毫秒数
 * param  int   year
 * param  int   month
 * param  int   day
 * param  int   hours
 * param  int   minutes
 */
function getTimes(year,month,day,hours,minutes){
    return Date.UTC(year, month, day, hours, minutes);
}


/**
 * 传递方法(封装的方法需在调用时先引入,再传递方法之后才能调用 前一参数为传递方法名,后一参数为实际方法名)
 */
module.exports = {
    apiRequest: apiRequest,
    refresh: refresh,
    mapTap:mapTap,
    getNowFormatDate: getNowFormatDate,
    getNowFormattime: getNowFormattime,
    getAppointDate: getAppointDate,
    getAppoint: getAppoint,
    getTimes: getTimes,
    login:login,
    getTimestamps: getTimestamps,
    baseUrl: baseUrl
}
